﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CommonTool
{
    /// <summary>
    /// 单例模式
    /// </summary>
    /// <typeparam name = "T" ></ typeparam >
    public class SingletonTemplate<T> where T : class, new()
    {


        #region 获取实例

        private static T m_instance;

        private static readonly object syslock;
        static SingletonTemplate()
        {
            SingletonTemplate<T>.syslock = new object();
        }

        /// <summary>获取实例</summary>
        /// <returns></returns>
        public static T GetInstance()
        {
            if ((object)SingletonTemplate<T>.m_instance == null)
            {
                lock (SingletonTemplate<T>.syslock)
                {
                    if ((object)SingletonTemplate<T>.m_instance == null)
                        SingletonTemplate<T>.m_instance = new T();
                }
            }
            return SingletonTemplate<T>.m_instance;
        }

        #endregion

        #region 线程

        //实例对象
        private Thread m_thread = null;

        //线程是否运行中
        protected bool m_bRunThread;

        /// <summary>线程函数</summary>
        public virtual void ThreadMonitor()
        {
            while (this.m_bRunThread)
            {
                Thread.Sleep(100);
                break;
            }
        }

        /// <summary>开始监视线程</summary>
        public void StartMonitor()
        {
            if (this.m_thread == null)
            {
                this.m_thread = new Thread(new ThreadStart(this.ThreadMonitor));
            }
            if (this.m_thread.ThreadState > System.Threading.ThreadState.Running)
            {
                this.m_bRunThread = true;
                this.m_thread.Start();
            }
        }

        /// <summary>结束监视线程</summary>
        public void StopMonitor()
        {
            if (this.m_thread != null)
            {
                this.m_bRunThread = false;
                if (!this.m_thread.Join(0x1388))
                {
                    this.m_thread.Abort();
                }
                this.m_thread = null;

            }
        }

        #endregion
    }
}
